var express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
var result = require('../models/result');
var config = require('../util/config');
var router = express.Router();

const textParser = bodyParser.text({ defaultCharset: 'utf-8' });  // Content-Type: text/plain

router.post('*', textParser, function (req, res, next) {
    var bodyArray = req.body.split(".");
    if (bodyArray.length != 3) {
        result.fail(res, 403, "参数格式错误");
        return;
    }
    var part0 = JSON.parse(new Buffer.from(bodyArray[0], 'base64').toString());
    var typ = part0.typ;
    var alg = part0.alg;
    if (typ !== 'JWT') {
        result.fail(res, 403, '参数错误');
        return;
    }
    if (alg === 'HS256') {
        var hmac = crypto.createHmac('SHA256', config.jwt.secret);
        var check = bodyArray[0] + '.' + bodyArray[1];
        var checkResult = hmac.update(check).digest("base64");
        if (checkResult !== bodyArray[2]) {
            result.fail(res, 403, '未知来源的访问');
        } else {
            var payload = JSON.parse(new Buffer.from(bodyArray[1], 'base64').toString());
            req.payload = payload;
            next();
        }
    } else {
        result.fail(res, 403, '不支持的算法');
    }
});

module.exports = router;